import React, { useState, useEffect, useMemo } from 'react';
import {
  Table,
  Card,
  PaginationProps,
  Button,
  Space,
  Typography,
  Tag,
  Modal,
} from '@arco-design/web-react';
import type { TableColumnProps } from '@arco-design/web-react';
import PermissionWrapper from '@/components/PermissionWrapper';
import {
  IconDelete,
  IconDownload,
  IconPlus,
} from '@arco-design/web-react/icon';
import SearchForm from './form';
import styles from './style/index.module.less';
import './mock';
import { useActivate, useAliveController } from 'react-activation';
import { useHistory } from 'react-router-dom';
import Api from '@/services/api';
import { DetailModal } from './detailModal';
import * as Model from '@/services/model';

function SearchTable() {
  const history = useHistory();

  const [data, setData] = useState([]);
  const [pagination, setPatination] = useState<PaginationProps>({
    sizeCanChange: true,
    showTotal: true,
    pageSize: 10,
    current: 1,
    pageSizeChangeResetCurrent: true,
  });
  const [loading, setLoading] = useState(true);
  const [formParams, setFormParams] = useState({});

  const [selectedOems, setSelectedOems] = useState<Model.Oem[]>([]);
  const [oemDetail, setOemDetail] = useState<Model.Oem | false>(false);
  const aliveController = useAliveController();
  useActivate(() => {
    console.log('active');
  });
  useEffect(() => {
    fetchData();
  }, [pagination.current, pagination.pageSize, JSON.stringify(formParams)]);

  const fetchData = () => {
    const { current, pageSize } = pagination;
    setLoading(true);
    Api.oemList({
      page: current,
      pageSize,
      ...formParams,
    })
      .then((res) => {
        setData(res.list);
        setPatination({
          ...pagination,
          current,
          pageSize,
          total: res.total,
        });
        setLoading(false);
      })
      .catch(() => {
        setLoading(false);
      });
  };

  const onChangeTable = ({ current, pageSize }) => {
    setPatination({
      ...pagination,
      current,
      pageSize,
    });
  };

  const handleSearch = (params) => {
    setPatination({ ...pagination, current: 1 });
    setFormParams({ ...params });
  };

  const handleDelete = (oems: Model.Oem[]) => {
    Modal.confirm({
      title: '确定删除以下主机厂吗？',
      content: (
        <div>
          <Typography.Text type="secondary">
            {oems.map((e) => e.name).join('，')}
          </Typography.Text>
        </div>
      ),
      onOk: () => {
        Api.deleteSuppliers(oems.map((e) => e.id)).then(() => {
          fetchData();
        });
      },
    });
  };

  const columns: TableColumnProps[] = [
    { title: '主机厂代码', dataIndex: 'id' },
    { title: '主机厂名称', dataIndex: 'name' },
    { title: '主机厂地址', dataIndex: 'address' },
    {
      title: '工作时间',
      width: 200,
      dataIndex: 'workPeriod',
      render(col) {
        return col.join(' ~ ');
      },
    },
    {
      title: '操作',
      render: (col, item) => {
        return (
          <Space>
            <Button
              size="small"
              type="primary"
              onClick={() => setOemDetail(item)}
            >
              编辑
            </Button>

            <Button
              size="small"
              type="primary"
              status="danger"
              onClick={() => handleDelete([item])}
            >
              删除
            </Button>
          </Space>
        );
      },
    },
  ];

  return (
    <Card>
      <SearchForm onSearch={handleSearch} />
      <div className={styles['button-group']}>
        <Space>
          <Button
            onClick={() => setOemDetail(new Model.Oem())}
            type="primary"
            icon={<IconPlus />}
          >
            新增主机厂
          </Button>
          <Button
            onClick={() => handleDelete(selectedOems)}
            type="primary"
            status="danger"
            disabled={selectedOems.length <= 0}
            icon={<IconDelete />}
          >
            删除主机厂
          </Button>
          <Button type="default" icon={<IconDownload />}>
            导出主机厂
          </Button>
        </Space>
      </div>
      <Table
        rowKey="id"
        loading={loading}
        onChange={onChangeTable}
        pagination={pagination}
        columns={columns}
        data={data}
        rowSelection={{
          type: 'checkbox',
          selectedRowKeys: selectedOems.map((e) => e.id),
          onChange: (selectedRowKeys, selectedRows) => {
            setSelectedOems(selectedRows);
          },
        }}
      />

      <DetailModal
        onCancel={() => setOemDetail(false)}
        onOk={() => setOemDetail(false)}
        oemInfo={oemDetail}
      />
    </Card>
  );
}

export default SearchTable;
